package cn.mulanbay.gateway.handler;

import cn.mulanbay.api.system.service.RemoteUserService;
import cn.mulanbay.business.bean.LoginUser;
import cn.mulanbay.business.handler.ThreadPoolHandler;
import cn.mulanbay.business.processor.LoginPersistentProcessor;
import cn.mulanbay.common.domain.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * 登录持久记录
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@Component
public class LoginPersistentHandler implements LoginPersistentProcessor {

    private static final Logger log = LoggerFactory.getLogger(LoginPersistentHandler.class);

    @Lazy
    @Autowired
    RemoteUserService remoteUserService;

    @Autowired
    ThreadPoolHandler threadPoolHandler;

    @Override
    public LoginUser loadLoginUser(String loginToken) {
        try {
            /**
             * Spring Cloud gateway无法直接使用OpenFeign，需要用异步的模式调用
             */
            Future<LoginUser> future = threadPoolHandler.submit(() -> {
                R<LoginUser> r = remoteUserService.loadLoginUser(loginToken);
                if(r.getCode()==0){
                    return r.getData();
                }else{
                    log.warn("从数据库中加载用户数据失败,code:{}",r.getCode());
                    return null;
                }
            });
            LoginUser user = future.get();
            if(user!=null){
                log.warn("从数据库中加载用户数据");
            }
            return user;
        } catch (Exception e) {
            log.error("加载登录用户异常",e);
        }
        return null;
    }
}
